<template>
  <el-popover
      placement="bottom"
      :width="200"
      trigger="click"
      popper-class="form-popover-container"
      :show-arrow="false"
  >
    <template #reference>
      <el-input v-model="value"></el-input>
    </template>
    <ul
        class="infinite-list"
        v-infinite-scroll="onLoad"
        infinite-scroll-distance="disabled"
        style="overflow:auto;"
    >
      <li v-for="item in options" @click="chooseOption(item.id)" :key="item.id" class="infinite-list-item">{{ item.label }}</li>
    </ul>
  </el-popover>
</template>

<script>
  export default {
    name: "SearchSelect",
    props: {
      options: {
        type: Array
      },
      value: {
        type: Object
      },
      load: {
        type: Function
      }
    },
    data(){
      return {
        disabled: false,
        page: {
          current: 1,
          total: 0
        }
      }
    },
    emits: ["update:options", "update:value"],
    methods:{
      async onLoad(){
        const rst = await this.load({
          page: this.page.current
        })
        this.$emit("update:options",[...this.options, ...rst.data]);
        this.page = {
          current: rst.page.current + 1,
          total: rst.page.total
        }
        if(this.page.total <= this.options.length + rst.data.length){
          this.disabled = true;
        }
      },
      chooseOption(val){
        this.$emit("update:value", val);
      }
    }
  }
</script>

<style>
  .form-popover-container{
    padding: 0 !important;
  }
  .form-popover-container ul{
    margin: 0;
    padding: 0;
  }
  .form-popover-container ul li{
    height: 34px;
    cursor: pointer;
    text-align: center;
    line-height: 34px;
    padding: 0 20px;
  }
  .form-popover-container ul li:hover{
    background: #F5F7FA;
  }
</style>